package {{basePackage}}.service.impl;

import {{basePackage}}.entity.{{entityName}};
import {{basePackage}}.dto.{{entityName}}DTO;
import {{basePackage}}.vo.{{entityName}}VO;
import {{basePackage}}.mapper.{{entityName}}Mapper;
import {{basePackage}}.service.{{entityName}}Service;
import {{basePackage}}.common.PageResult;
import {{basePackage}}.common.BusinessException;
import {{basePackage}}.common.ErrorCode;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * {{tableComment}} 服务实现类
 * 
 * @author {{author}}
 * @version {{version}}
 * @since {{createTime}}
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class {{entityName}}ServiceImpl extends ServiceImpl<{{entityName}}Mapper, {{entityName}}> implements {{entityName}}Service {

    @Override
    public PageResult<{{entityName}}VO> page(Integer pageNum, Integer pageSize, {{entityName}}DTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<{{entityName}}> queryWrapper = new LambdaQueryWrapper<>();
        
        // 动态查询条件构建
        if (queryDTO != null) {
{{#each queryFields}}
            // {{comment}}查询条件
{{#if (eq javaType "String")}}
            if (StringUtils.hasText(queryDTO.get{{upperFirst fieldName}}())) {
{{#if (eq queryType "like")}}
                queryWrapper.like({{../entityName}}::get{{upperFirst fieldName}}, queryDTO.get{{upperFirst fieldName}}());
{{else}}
                queryWrapper.eq({{../entityName}}::get{{upperFirst fieldName}}, queryDTO.get{{upperFirst fieldName}}());
{{/if}}
            }
{{else}}
            if (queryDTO.get{{upperFirst fieldName}}() != null) {
{{#if (eq queryType "like")}}
                queryWrapper.like({{../entityName}}::get{{upperFirst fieldName}}, queryDTO.get{{upperFirst fieldName}}());
{{else}}
    {{#if (eq queryType "ge")}}
                queryWrapper.ge({{../entityName}}::get{{upperFirst fieldName}}, queryDTO.get{{upperFirst fieldName}}());
    {{else}}
        {{#if (eq queryType "le")}}
                queryWrapper.le({{../entityName}}::get{{upperFirst fieldName}}, queryDTO.get{{upperFirst fieldName}}());
        {{else}}
                queryWrapper.eq({{../entityName}}::get{{upperFirst fieldName}}, queryDTO.get{{upperFirst fieldName}}());
        {{/if}}
    {{/if}}
{{/if}}
            }
{{/if}}
{{/each}}
        }
        
        // 默认按创建时间倒序
        queryWrapper.orderByDesc({{entityName}}::getCreateTime);
        
        // 分页查询
        IPage<{{entityName}}> page = new Page<>(pageNum, pageSize);
        IPage<{{entityName}}> result = this.page(page, queryWrapper);
        
        // 转换为VO
        List<{{entityName}}VO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageResult.<{{entityName}}VO>builder()
                .records(voList)
                .total(result.getTotal())
                .current(result.getCurrent())
                .size(result.getSize())
                .pages(result.getPages())
                .build();
    }

    @Override
    public {{entityName}}VO getById(Long id) {
        {{entityName}} entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "{{tableComment}}不存在");
        }
        return convertToVO(entity);
    }

    @Override
    public {{entityName}}VO create({{entityName}}DTO {{#lowerCase}}{{entityName}}{{/lowerCase}}DTO) {
        // 参数验证
        validateDTO({{#lowerCase}}{{entityName}}{{/lowerCase}}DTO);
        
        // 转换为实体
        {{entityName}} entity = convertToEntity({{#lowerCase}}{{entityName}}{{/lowerCase}}DTO);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.save(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "创建{{tableComment}}失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public {{entityName}}VO update(Long id, {{entityName}}DTO {{#lowerCase}}{{entityName}}{{/lowerCase}}DTO) {
        // 检查记录是否存在
        {{entityName}} existingEntity = this.getById(id);
        if (existingEntity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "{{tableComment}}不存在");
        }
        
        // 参数验证
        validateDTO({{#lowerCase}}{{entityName}}{{/lowerCase}}DTO);
        
        // 更新实体
        {{entityName}} entity = convertToEntity({{#lowerCase}}{{entityName}}{{/lowerCase}}DTO);
        entity.setId(id);
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.updateById(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "更新{{tableComment}}失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public void delete(Long id) {
        // 检查记录是否存在
        {{entityName}} entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "{{tableComment}}不存在");
        }
        
        // 删除
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "删除{{tableComment}}失败");
        }
    }

    @Override
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "删除ID列表不能为空");
        }
        
        // 批量删除
        boolean success = this.removeByIds(ids);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "批量删除{{tableComment}}失败");
        }
    }

    // 关联关系查询方法将在后续版本中支持

    /**
     * 实体转VO
     */
    private {{entityName}}VO convertToVO({{entityName}} entity) {
        if (entity == null) {
            return null;
        }
        
        {{entityName}}VO vo = new {{entityName}}VO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    /**
     * DTO转实体
     */
    private {{entityName}} convertToEntity({{entityName}}DTO dto) {
        if (dto == null) {
            return null;
        }
        
        {{entityName}} entity = new {{entityName}}();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    /**
     * 验证DTO参数
     */
    private void validateDTO({{entityName}}DTO dto) {
        if (dto == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "{{tableComment}}信息不能为空");
        }
        
        // 必填字段验证
{{#each requiredFields}}
{{#if (eq javaType "String")}}
        if (!StringUtils.hasText(dto.get{{upperFirst fieldName}}())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "{{comment}}不能为空");
        }
{{else}}
        if (dto.get{{upperFirst fieldName}}() == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "{{comment}}不能为空");
        }
{{/if}}
{{/each}}
    }
}
